package cn.project.domain.strategy.service.rule.tree.impl;

import cn.project.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.project.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import cn.project.domain.strategy.repository.IStrategyRepository;
import cn.project.domain.strategy.service.armory.IStrategyDispatch;
import cn.project.domain.strategy.service.rule.tree.ILogicTreeNode;
import cn.project.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author xu
 * @description 库存节点
 * @date 2025/7/8
 */
@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyDispatch strategyDispatch;
    @Resource
    private IStrategyRepository strategyRepository;
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId,String ruleValue){
        log.info("规则树 库存节点处理 userId:{} strategyId:{} awardId:{} ruleValue{}", userId, strategyId, awardId, ruleValue);
        // 扣减库存
        Boolean status = strategyDispatch.subtractionAwardStock(strategyId, awardId);
        if(status){
            log.info("库存扣减成功 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
            strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                    .strategyId(strategyId)
                    .awardId(awardId)
                    .build());
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue("")
                            .build())
                    .build();
        }
        // 库存不足，走兜底
        log.info("库存不足 扣减失败 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .build();
    }
}
